#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_freertos_hooks.h"
#include "esp_log.h"

#include "E:\app\Espressif\frameworks\esp-idf-v5.0.1\components\esp_timer\include/esp_timer.h"

#include "../lvgl/lvgl.h"
#include "lv_port_disp.h"
#include "lv_port_indev.h"

#include "../ui/ui.h"

#define LV_TICK_PERIOD_MS 1

#define TAG "lv_port"


void lv_tick_task(void *arg)
{
	(void) arg;
	lv_tick_inc(1);
}

void lv_port_tick_init(void)
{
	const esp_timer_create_args_t periodic_timer_args = {
			.callback = &lv_tick_task,
			.name = "lv_tick_task"};
	esp_timer_handle_t periodic_timer;

	ESP_ERROR_CHECK(esp_timer_create(&periodic_timer_args, &periodic_timer));
	ESP_ERROR_CHECK(
			esp_timer_start_periodic(periodic_timer, LV_TICK_PERIOD_MS * 1000));
}

static void lvgl_task(void *args)
{
	(void) args;
    ESP_LOGI(TAG, "Initializing lv");
    lv_init();

    ESP_LOGI(TAG, "Initializing lv_disp");

    lv_port_disp_init();
    lv_port_indev_init();
	lv_port_tick_init();
	ui_init();
	//lv_demo_benchmark();
    while (1) {
        lv_task_handler();
        vTaskDelay(pdMS_TO_TICKS(LV_TICK_PERIOD_MS));
    }
    vTaskDelete(NULL);
}

void lvgl_init()  {
    ESP_LOGI(TAG, "Creating lvgl task");
    xTaskCreatePinnedToCore(lvgl_task, "lvgl", 4096, NULL, CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT-1, NULL, 1);
}
